package com.coocaa.x.uipackage.widget;

import android.content.Context;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

import com.coocaa.x.uipackage.utils.CoocaaFresco;
import com.facebook.common.internal.Supplier;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.interfaces.SimpleDraweeControllerBuilder;
import com.facebook.drawee.view.GenericDraweeView;

/**
 * Created by luwei on 15-11-25.
 */
public class CoocaaDraweeView extends GenericDraweeView {
    private static Supplier<? extends SimpleDraweeControllerBuilder> sDraweeControllerBuilderSupplier;

    /** Initializes {@link CoocaaDraweeView} with supplier of Drawee controller builders. */
    public static void initialize(
            Supplier<? extends SimpleDraweeControllerBuilder> draweeControllerBuilderSupplier) {
        sDraweeControllerBuilderSupplier = draweeControllerBuilderSupplier;
    }

    /** Shuts {@link CoocaaDraweeView} down. */
    public static void shutDown() {
        sDraweeControllerBuilderSupplier = null;
    }

    private SimpleDraweeControllerBuilder mSimpleDraweeControllerBuilder;
    public CoocaaDraweeView(Context context, GenericDraweeHierarchy hierarchy) {
        super(context, hierarchy);
        init(context);
    }

    public CoocaaDraweeView(Context context) {
        super(context);
        init(context);
    }

    public CoocaaDraweeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CoocaaDraweeView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        if (isInEditMode()) {
            return;
        }
        mSimpleDraweeControllerBuilder = CoocaaFresco.newDraweeControllerBuilder(context.getApplicationContext());
    }

    protected SimpleDraweeControllerBuilder getControllerBuilder() {
        return mSimpleDraweeControllerBuilder;
    }

    /**
     * Displays an image given by the uri.
     *
     * @param uri uri of the image
     * @undeprecate
     */
    @Override
    public void setImageURI(Uri uri) {
        setImageURI(uri, null);
    }

    /**
     * Displays an image given by the uri.
     *
     * @param uri uri of the image
     * @param callerContext caller context
     */
    public void setImageURI(Uri uri, @Nullable Object callerContext) {
        DraweeController controller = mSimpleDraweeControllerBuilder
                .setCallerContext(callerContext)
                .setUri(uri)
                .setOldController(getController())
                .build();
        setController(controller);
    }
}
